<?php

namespace App\Http\Controllers\Admin;

use App\Services\WxUserTagService;
use Illuminate\Http\Request;

/**
 * 微信用户组管理
 * @package App\Http\Controllers\Admin
 */
class WxUserTagController extends BaseController
{
    private $userTagSer;
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->userTagSer = new WxUserTagService();
    }

    /**
     * 微信标签管理
     */
    public function index(Request $request)
    {
        if ($request->ajax()){
            $tagList = $this->userTagSer->getTagList();
            $newlist = [];
            foreach ($tagList as $k => $v){
                $v['text'] = $v['tag_name'];
                $v['icon'] = 'glyphicon glyphicon-bookmark';
                $v['tags'] = ['用户数：'.$v['user_count'],'排序：'.$v['order_num']];
                $newlist[$k] = $v->toArray();
            }

            //树结构菜单列表
            $tree = new \App\Services\TreeService('tag_id', 'parent_id', 'nodes');
            $tree->load($newlist);
            $treeMenuList = $tree->deepTree();
            $data['treeList'] = $treeMenuList ? $treeMenuList : [];
            return $data;
        }
        return view('admin.wxusertag.index', $this->viewData);
    }

    /**
     * 用户标签
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function save(\App\Http\Requests\AdminWxUserTagPost $request){
        try {
            $rs = $this->userTagSer->saveData($request);
            if ($rs) {
                return $this->showMsg('success', ($request->input('tag_id') ? '编辑' : '添加') . '成功', [], 'admin.sysmenu.index');
            }
            throw new \Exception(($request->input('tag_id') ? '编辑' : '添加') . '菜单失败');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }

    /**
     * 删除标签
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        try {
            $id = $request->input('id', 0);
            if (!$id) {
                throw new \Exception('请指定要删除的标签');
            }
            $rs = $this->userTagSer->del($id);
            if (!$rs) {
                throw new \Exception('删除失败');
            }
            return $this->showMsg('success', '删除成功');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }

    /**
     * 同步标签数据
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function sync()
    {
        try {
            $rs = $this->userTagSer->sync();
            if ($rs) {
                return $this->showMsg('success', '同步标签成功', [], 'admin.wxusertag.index');
            }
            throw new \Exception('同步标签失败');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }
}
